package com.xiaoshuidi.cloud.module.bpm.job.xxljob;

import cn.hutool.core.util.ObjectUtil;
import com.xiaoshuidi.cloud.framework.common.util.json.JsonUtils;
import com.xiaoshuidi.cloud.framework.tenant.core.aop.TenantIgnore;
import com.xiaoshuidi.cloud.framework.tenant.core.context.TenantContextHolder;
import com.xiaoshuidi.cloud.framework.tenant.core.job.TenantJob;
import com.xiaoshuidi.cloud.framework.tenant.core.service.TenantFrameworkService;
import com.xiaoshuidi.cloud.module.bpm.dal.dataobject.reserveapartmentconfig.ReserveApartmentConfig;
import com.xiaoshuidi.cloud.module.bpm.service.reserveapartmentconfig.ReserveApartmentConfigService;
import com.xiaoshuidi.cloud.module.rooms.api.apartment.ApartmentApi;
import com.xiaoshuidi.cloud.module.rooms.api.apartment.vo.GetApartmentVO;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Component
@RequiredArgsConstructor
@TenantJob
public class InitReserveApartmentConfigJob {

    private final ReserveApartmentConfigService reserveApartmentConfigService;
    private final ApartmentApi apartmentApi;
    private final TenantFrameworkService tenantFrameworkService;

    @XxlJob("init-reserve-apartment-config")
    @TenantIgnore
    public void initReserveApartmentConfig(){
        Long tenantId = TenantContextHolder.getTenantId();
        List<Long> tenantIds = tenantFrameworkService.getTenantIds();
        log.info("[初始化预约配置]--开始,tenantId:{},tenantIds:{}", tenantId, tenantIds);
        List<GetApartmentVO> apartmentList = apartmentApi.getAllApartment().getCheckedData();
        // 只配置集中式门店
        apartmentList = apartmentList.stream().filter(p -> ObjectUtil.isNotEmpty(p.getIsConcentrated()) && p.getIsConcentrated()).collect(Collectors.toList());
        log.info("[初始化预约配置],tenantId:{},集中式门店列表:{}", tenantId, JsonUtils.toJsonString(apartmentList));
        List<ReserveApartmentConfig> reserveApartmentConfigs = new ArrayList<>();
        apartmentList.forEach(apartment -> {
            for (int i = 1; i < 7; i++) {
                ReserveApartmentConfig reserveApartmentConfig = new ReserveApartmentConfig();
                reserveApartmentConfig.setApartmentId(apartment.getId());
                reserveApartmentConfig.setApartmentName(apartment.getName());
                reserveApartmentConfig.setDeptId(apartment.getDeptId());
                reserveApartmentConfig.setTimePeriod(i);
                reserveApartmentConfigs.add(reserveApartmentConfig);
            }
        });
        reserveApartmentConfigService.saveBatch(reserveApartmentConfigs);
        log.info("[初始化预约配置]--完成");
    }

}
